// src/utils/http.js 中  
import axios from "axios"
import {
	UniAdapter
} from "uniapp-axios-adapter"
import store from '@/store'
import {
	getToken,
	setToken
} from '@/util/auth'

const baseURL = 'https://api.zesi.com.cn/api'
const request = axios.create({
	baseURL,
	timeout: 6000,
	adapter: UniAdapter,
});

request.interceptors.request.use((config) => {
		if (store.getters.token) {
			config.headers['Authorization'] = `${getToken()}`
			config.headers['token'] = `${getToken()}`
		}
		return config;
	},
	error => {
		return Promise.reject(error);
	});

request.interceptors.response.use((response) => {
	// 统一处理响应,返回Promise以便链式调用  
	if (response.status === 200) {
		const { data } = response;
		if (data && data.errorCode === 0) {
			return Promise.resolve(data);
		} else {
			uni.showToast({
				title: data.msg || res_msg,
				icon:'none'
			})
			return Promise.reject(data);
		}
	} else {
		// #ifdef MP
		if (response.status === 401 || response.data.errorCode === -1) {
			wx.login({
				success: res => {
					uni.request({
						url: baseURL + '/auth/token',
						method: 'GET',
						data: {
							code: res.code
						},
						success: res => {
							const token = res.data.data
							store.commit('user/SET_TOKEN', token)
							setToken(token)
							store.dispatch('user/getInfo')
							setTimeout(() => {
								response.config.headers.token = `${getToken()}`
								axios.request(response.config)
							},1000)
						},
						fail: error => {
							console.log(error)
						}
					})
				}
			})
		} else {
			let message = response.data.msg || '请求失败'
		}
		// #endif
		uni.showToast({
			title: response.data.msg || res_msg,
			icon:'none'
		})
		return Promise.reject(response);
	}
});

export default request;
